package com.can.runner;

import com.can.domain.entity.Article;
import com.can.mapper.ArticleMapper;
import com.can.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.can.constant.SystemConstants.ARTICLE_VIEWCOUNT_REDIS_PREFIX;

@Component
public class ViewCountRunner implements CommandLineRunner {

    @Resource
    private ArticleMapper articleMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        //查询博客信息  id  viewCount
        List<Article> articles = articleMapper.selectList(null);
        Map<String, Integer> viewCountMap = articles.stream()
                .collect(Collectors.toMap(
                                article -> article.getId().toString(),
                                // article.getViewCount()是Long类型,最后进入redis就是 4L,所以需要先转换为int
                                article -> article.getViewCount().intValue())
                );
        //存储到redis中
        redisCache.setCacheMap(ARTICLE_VIEWCOUNT_REDIS_PREFIX, viewCountMap);
    }

}
